package cn.map.utils.encryption;

import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.pkcs.RSAPublicKey;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;

import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;

/**
 * @author 後溪
 */
public class RSATrans {
    /**
     * 公钥PKCS1转PKCS8
     * @param pkcs1PublicKeyByte 公钥
     * @return
     */
    public static byte[] publicKeyPKCS1ToPKCS8(byte[] pkcs1PublicKeyByte) {

        RSAPublicKey rsaPub = RSAPublicKey.getInstance(pkcs1PublicKeyByte);
        byte[] pkcs8Bytes = null;
        try {
            KeyFactory kf = KeyFactory.getInstance("RSA");

            PublicKey generatePublic = kf.generatePublic(new RSAPublicKeySpec(rsaPub.getModulus(), rsaPub.getPublicExponent()));

            pkcs8Bytes = generatePublic.getEncoded();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return pkcs8Bytes;
    }

    /**
     * 私钥PKCS1转PKCS8
     * @param pkcs1PrivateKeyByte 私钥
     * @return
     */
    public static byte[] privateKeyPKCS1ToPKCS8(byte[] pkcs1PrivateKeyByte) {

        AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PKCSObjectIdentifiers.pkcs8ShroudedKeyBag);

//        RSAPrivateKey privateKey = RSAPrivateKey.getInstance(pkcs1PrivateKeyByte);
        //另一种方式
        ASN1Sequence privateKey = ASN1Sequence.getInstance(pkcs1PrivateKeyByte);

        byte[] pkcs8Bytes = null;

        try {
            PrivateKeyInfo privKeyInfo = new PrivateKeyInfo(algorithmIdentifier, privateKey);
            pkcs8Bytes = privKeyInfo.getEncoded();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pkcs8Bytes;
    }
}
